package com.sky.config;


import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Setmeal;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;

@Configuration
public class BloomFilterConfig {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 初始化布隆过滤器
     * @return
     */
    @Bean
    public BloomFilter<Long> setmealBloomFilter(){
        //获取所有套餐
        List<Setmeal> setmeals = setmealService.list(new Setmeal());
        //创建布隆过滤器
        BloomFilter<Long> bloomFilter = BloomFilter.create(Funnels.longFunnel(), Math.max(setmeals.size(), 1000), 0.01);
        //添加数据至布隆过滤器中
        for (Setmeal setmeal : setmeals) {
            bloomFilter.put(setmeal.getId());
        }

        System.out.println("布隆过滤器初始化完成");
        return bloomFilter;
    }

    @Bean
    public BloomFilter<Long> categoryBloomFilter(){
        //获取所有分类
        PageResult pageResult = categoryService.pageQuery(new CategoryPageQueryDTO());
        List<Category> records = pageResult.getRecords();
        BloomFilter<Long> bloomFilter = BloomFilter.create(Funnels.longFunnel(), Math.max(records.size(), 1000), 0.01);
        for (Category record : records) {
            bloomFilter.put(record.getId());
        }
        System.out.println("布隆过滤器初始化完成");
        return bloomFilter;
    }


}
